<template>
  <div class="container">
    <div class="header">
      <h2 class="header_title">宠物管理</h2>
      <span>用于管理小区里的宠物信息，包括业主、家庭成员及租户饲养的宠物</span>
    </div>
    <!-- 查询数据 -->
    <el-card>
      <el-row :gutter="15" class="searchForm">
        <el-form
          ref="elForm"
          :model="formData"
          size="medium"
          label-width="97px"
          label-position="top"
        >
          <el-row type="flex" justify="start" class="search">
            <el-col :span="4">
              <el-form-item label="宠物名称">
                <el-input
                  v-model="formData.name"
                  placeholder="请输入"
                  clearable
                  size="small"
                  :style="{ width: '100%' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="小区名称">
                <el-select
                  v-model="formData.community_code"
                  placeholder="请选择"
                  clearable
                  size="small"
                  :style="{ width: '100%' }"
                  @change="getBuild"
                >
                  <el-option
                    v-for="item in community_codeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="栋数">
                <el-select
                  v-model="formData.building_code"
                  placeholder="请输入"
                  clearable
                  size="small"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in build_codeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="收养时间" prop="name">
                <el-date-picker
                  v-model="time"
                  type="daterange"
                  size="small"
                  format="yyyy-MM-dd"
                  value-format="timestamp"
                  :style="{ width: '100%' }"
                  start-placeholder="请选择"
                  end-placeholder="请选择"
                  range-separator="-"
                  clearable
                  @change="getTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8" class="onBtn">
              <el-form-item class="botn">
                <el-button @click="onReset">重置</el-button>
                <el-button type="primary" @click="petList(formData)">查询</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </el-card>

    <!-- 表格 -->
    <el-card class="tableCard">
      <el-button
        style="float: right; padding: 10px 20px;margin-right:80px"
        type="primary"
        size="small"
        :disabled="!checkBtnPermission('/owners/pet','create')"
        @click="$refs.addForm.dialogShow = true"
      >新增宠物</el-button>
      <el-table
        :data="list"
        style="width: 100%"
      >
        <el-table-column prop="name" label="宠物名称" />
        <el-table-column prop="color" label="宠物颜色" />

        <el-table-column prop="photo" label="宠物照片">
          <template v-slot="{row}">
            <img
              :src="getPhoto(row.photo)[0]"
              style="width:54px;height:54px;"
              @click="previewImg(getPhoto(row.photo))"
            >
          </template>

        </el-table-column>
        <el-table-column prop="community.name" label="小区名称" />

        <el-table-column prop="building.name" label="栋数" />
        <el-table-column prop="member.name" label="主人姓名" />
        <el-table-column prop="member.tel" label="联系方式" />
        <el-table-column prop="remark" label="描述" />
        <el-table-column prop="adopt_time" label="收养时间">
          <template v-slot="{row}">
            {{ timeSet(row.adopt_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200">
          <template slot-scope="{ row }">
            <el-button class="text" :disabled="!checkBtnPermission('/owners/pet','update')" @click="editRow(row.id)">编辑</el-button>
            <el-button class="text" :disabled="!checkBtnPermission('/owners/pet','destroy')" @click="delRow(row.id)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
      <!-- 分页 -->
      <div class="fenye">
        <div class="pageInfo">
          第{{ startCount }}-{{ endCount }}条/总共{{ total||0 }}条
        </div>
        <el-pagination
          class="pagination"

          layout="prev, pager, next"

          :total="total"
          :page-size="formData.pageSize"
          :current-page="page"
          @size-change="sizeChange"
          @current-change="currentChange"
        />
        <div v-if="jump">跳到
          <input v-model.number="pages" style="width:25px" @change="pageChange(pages)">
          页
        </div>
      </div>
    </el-card>

    <!-- 新增、修改弹框区域 -->
    <addFormPet
      ref="addForm"
      :seeimage1="seeImage"
      @updateList="petList"
    />
  </div>

</template>

<script>
import { communityInfo, communityBuild } from '@/api/owers/owers'
import { petList, delPet, getPet } from '@/api/owers/pet'
import addFormPet from './component/addFormPet.vue'
export default {
  name: 'OwnerPet',
  components: {
    addFormPet
  },
  data() {
    return {
      imges: require('@/assets/images/isno.png'),
      seeImage: [],
      // 表单值
      formData: {
        current: 1,
        pageSize: 10,
        adopt_time: '',
        community_code: '',
        building_code: '',
        name: ''
      },
      time: '', // 临时存储时间
      page: 1, // 分页当前页码
      pages: 1, // 跳到第几页页码
      // 小区下拉框
      community_codeOptions: [],
      list: [], // 数据列表
      total: null, // 列表总数
      // 栋数
      build_codeOptions: [],
      genderList: [{ id: 0, sex: '男' }, { id: 1, sex: '女' }],
      ownerList: [{ id: 1, owner: '业主' }, { id: 2, owner: '家庭成员' }, { id: 3, owner: '租户' }],
      // 控件显示隐藏
      seShow: true,
      offset: 0
    }
  },
  computed: {
    // 显示跳到第几页
    jump() {
      return (this.total / this.formData.pageSize) > 1
    },
    startCount() {
      if (this.list.length) {
        return this.formData.current === 1 ? this.formData.current : (this.formData.current - 1) * this.formData.pageSize + 1
      }
      return 0
    },
    endCount() {
      if (this.list.length) {
        return this.formData.current === 1 ? this.list.length : (this.formData.current - 1) * this.formData.pageSize + this.list.length
      }
      return 0
    }
  },
  watch: {},
  created() {
    this.communityInfo()
    this.petList()
  },
  mounted() {},
  methods: {
    // 跳到第几页
    pageChange(val) {
      // console.log(Math.ceil(this.total / 2))
      // console.log(!(Math.ceil(this.total / 2) >= val))
      if (!(Math.ceil(this.total / this.formData.pageSize) >= val)) {
        this.pages = this.page
        return
      }

      if (typeof val !== 'number') return this.$message.warning('请输入数字')
      // console.log(val)
      // console.log('this.input', this.page)
      this.page = +val
      this.currentChange(this.page)
    },
    // 图片预览
    previewImg(url) {
      // 单图预览
      if (url.length === 1) {
        this.$hevueImgPreview({
          url: url[0]
        })
      } else {
        // # 多图预览
        this.$hevueImgPreview({
          multiple: true, // 开启多图预览模式
          nowImgIndex: 0, // 多图预览，默认展示第二张图片
          imgList: url // 需要预览的多图数组
        })
      }
    },
    // 图片格式化
    getPhoto(val) {
      const imgAll = []
      if (val) {
        // 多图
        if (val.includes(',')) {
          return val
            .split(',')
            .map((item) => 'http://124.223.14.236:8881' + item)
        } else {
          // 单图
          imgAll.push('http://124.223.14.236:8881' + val)
          return imgAll
        }
      } else {
        // 无图
        imgAll.push(this.imges)
        return imgAll
      }
    },
    // 每页数量变化的时候
    sizeChange(newSize) {
      // newSize 最新的每页数量
      this.formData.pageSize = newSize
      // 拉取列表
      this.petList()
    },
    // 页码变化事件
    currentChange(newPage) {
      console.log(+this.page)
      if (!newPage) return
      this.page = +newPage
      // newPage 最新的页码
      this.formData.current = newPage
      // 拉取列表
      this.petList()
    },
    // 处理图片
    showImgSrc(url) {
      return 'http://124.223.14.236:8881' + url
    },
    // 处理时间
    timeSet(time) {
      return new Date(time).toLocaleString()
    },
    // 处理成员类型
    ownerType(type) {
      if (type === 1) {
        return '业主'
      } else if (type === 2) {
        return '家庭成员'
      } else {
        return '租户'
      }
    },
    // 获取列表
    async petList() {
      const res = await petList(this.formData)
      console.log('获取列表', res)
      this.list = res.data.data.rows
      this.total = res.data.data.count
    },
    // 获取小区
    async communityInfo() {
      const res = await communityInfo()
      // console.log('获取小区', res.data.data)
      this.community_codeOptions = res.data.data
    },
    // 选择框改变获取小区对应楼栋
    async getBuild(val) {
      // console.log(val)
      this.$set(this.formData, 'building_code', '')
      const res = await communityBuild(val)
      // console.log('选择框改变获取小区对应楼栋', res)
      this.build_codeOptions = res.data.data
    },
    // 处理时间
    getTime(val) {
      // console.log(val)
      const time = []
      time.push(val[0])
      time.push(val[1])
      // console.log(time)
      this.formData.adopt_time = time.join(',')
    },
    // 修改数据
    async editRow(id) {
      console.log('获取该行数据', id)
      // 获取该行数据
      const res = await getPet(id)
      console.log('获取该行数据', res)
      // 赋值给表单
      this.$refs.addForm.formData = res.data.data
      // 如果有图片，赋值给seeImage做回显
      if (this.$refs.addForm.formData.photo) {
        const val = (this.$refs.addForm.formData.photo || '').split(',')
        this.$refs.addForm.imgList = val
        val.forEach(item => {
          this.seeImage.push({ url: 'http://124.223.14.236:8881' + item })
        })
      }
      // 回显楼栋等信息
      this.$refs.addForm.getBuild(res.data.data.community_code)
      this.$refs.addForm.getHouse(res.data.data.building_code)
      this.$refs.addForm.getMember(res.data.data.house_code)
      // 打开弹框
      this.$refs.addForm.dialogShow = true
    },
    // 删除数据
    async delRow(id) {
      // 弹出确认框
      await this.$confirm('确认删除吗')
      // 发生删除请求
      await delPet(id)
      // 提示成功
      this.$message.success('删除成功')
      // 边缘问题：如果不是第一页，且这一页只有一个，且删除成功，页码需要-1
      if (this.formData.current > 1 && this.list.length === 1) {
        this.formData.current--
      }
      // 列表更新  重新拉取列表
      this.petList()
    },
    // 搜索重置
    onReset() {
      // 重置搜索表单
      this.formData = {
        current: 1,
        pageSize: 10,
        adopt_time: '',
        community_code: '',
        building_code: '',
        name: ''
      }
      // 时间为空
      this.time = ''
      // 拉取列表
      this.petList()
    },

    // 收起
    packUp() {
      this.seShow = !this.seShow
      this.offset = this.seShow ? 0 : 12
    }

  }
}
</script>
<style lang="scss" scoped>
.fenye{
  display: flex;
    align-items: center;
  justify-content: flex-end;

.pagination{
  display: inline-block;
  margin: 10px 0;
}
}
.tableCard{
  margin-top: 20px;
}

.container{
  padding: 20px;
  .header{
    margin-bottom: 5px;
    .header_title{
      display: inline-block;
      margin-right: 10px;
    }
    span{
      color: #575758;
    }
  }
  .text{
    border: 0;
    color: #0092fc;
    cursor: pointer;
    margin-right: 10px;
  }
}
.searchForm {
  .search {
    flex-wrap: wrap;
    .el-col {
      padding: 0 10px;
    }
    .right-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .packup {
        cursor: pointer;
        color: #1890ff;
      }
    }
  }
}
.onBtn{
  display: flex;
justify-content: flex-end;
.botn {
  display: flex;
align-items: center;
        height: 100%;
        .el-button {
          // display: block;
          margin-top: 5px;
          margin-left: 0;
          margin-right: 5px;
        }
      }
}
</style>
